//
//  LatDetailsViewController.m
//  project_delicious
//
//  Created by 章历杰 on 15/3/24.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "LatDetailsViewController.h"
#import "HotShop.h"
#import "UIColor+AddColor.h"
#import "HotShopsViewController.h"
#import "MBProgressHUD.h"
@interface LatDetailsViewController ()
@property (nonatomic, retain) UIScrollView *scrollV;
@property (nonatomic, retain) MBProgressHUD *HUD;
//添加的两个收藏的属性--------------
@property (nonatomic, retain) UIImageView *myFavorImageView;
@property (nonatomic, retain) NSString *nameTitle;
@property (nonatomic, assign) BOOL flag;
@property (nonatomic, retain) NSString *str;
//--------------------
@end

@implementation LatDetailsViewController

- (void)dealloc
{
    //添加属性的释放
    [_str release];
    [_myFavorImageView release];
    [_nameTitle release];
    //
    
    [_num release];
    [_dataDic release];
    [_scrollV release];
    [_HUD release];
    
    //[_favoCount release];
    //[_details release];
    [super dealloc];
}
//解析数据
- (void)startAnalyze:(NSString *)str
{
    
    
    self.scrollV = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollV.showsVerticalScrollIndicator = NO;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //NSLog(@"成功");
        self.dataDic = [responseObject objectForKey:@"data"];
        //菜的图片
        UIImageView *dishPic = [[UIImageView alloc] initWithFrame:CGRectMake(15, 70, self.scrollV.frame.size.width*4/5-50, 250)];
        NSString *string = [[self.dataDic objectForKey:@"dish_detail_item"] objectForKey:@"main_photo_url"];
        string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:string];
        [dishPic setImageWithURL:url];
        dishPic.layer.cornerRadius = 30;
        dishPic.layer.masksToBounds = YES;
        [self.scrollV addSubview:dishPic];
        [dishPic release];
        
        //味&评分
        
        UIImageView *taste = [[UIImageView alloc] initWithFrame:CGRectMake(dishPic.frame.origin.x+dishPic.frame.size.width+10, 80, 40, 40)];
        taste.image = [UIImage imageNamed:@"taste.png"];
        taste.layer.cornerRadius = 20;
        taste.layer.masksToBounds = YES;
        [self.scrollV addSubview:taste];
        [taste release];
        UIImageView *tasteScore = [[UIImageView alloc]  initWithFrame:CGRectMake(taste.frame.origin.x+50, 85, 20, 30)];
        NSString *ts = [[self.dataDic objectForKey:@"dish_detail_item"] objectForKey:@"taste_score"];
        NSInteger a = [ts integerValue];
        if (a == 5) {
            tasteScore.image = [UIImage imageNamed:@"scoreFive"];
        }else if (a == 4) {
            tasteScore.image = [UIImage imageNamed:@"scoreFour"];
        }else if (a == 3) {
            tasteScore.image = [UIImage imageNamed:@"scoreThree"];
        }else if (a == 2) {
            tasteScore.image = [UIImage imageNamed:@"scoreTwo"];
        }else if (a == 1) {
            tasteScore.image = [UIImage imageNamed:@"scoreOne"];
        }else if ((a == 0) || ts == nil) {
            tasteScore.image = [UIImage imageNamed:@"scoreZero.png"];
        }
        [self.scrollV addSubview:tasteScore];
        [tasteScore release];
        
        //视&评分
        
        UIImageView *impression = [[UIImageView alloc] initWithFrame:CGRectMake(taste.frame.origin.x, 180, 40, 40)];
        impression.image = [UIImage imageNamed:@"impression.png"];
        impression.layer.cornerRadius = 20;
        impression.layer.masksToBounds = YES;
        [self.scrollV addSubview:impression];
        [impression release];
        UIImageView *impressionScore = [[UIImageView alloc] initWithFrame:CGRectMake(impression.frame.origin.x+50, 185, 20, 30)];
        NSString *ts2 = [[self.dataDic objectForKey:@"dish_detail_item"] objectForKey:@"impressions_score"];
        NSInteger a2 = [ts integerValue];
        if (a2 == 5) {
            impressionScore.image = [UIImage imageNamed:@"scoreFive.png"];
        }else if (a2 == 4) {
            impressionScore.image = [UIImage imageNamed:@"scoreFour.png"];
        }else if (a2 == 3) {
            impressionScore.image = [UIImage imageNamed:@"scoreThree.png"];
        }else if (a2 == 2) {
            impressionScore.image = [UIImage imageNamed:@"scoreTwo.png"];
        }else if (a2 == 1) {
            impressionScore.image = [UIImage imageNamed:@"scoreOne.png"];
        }else if ((a2 == 0) || ts2 == nil) {
            impressionScore.image = [UIImage imageNamed:@"scoreZero.png"];
        }
        [self.scrollV addSubview:impressionScore];
        [impressionScore release];
        
        //口&评分
        
        UIImageView *texture = [[UIImageView alloc] initWithFrame:CGRectMake(taste.frame.origin.x, 270, 40, 40)];
        texture.image = [UIImage imageNamed:@"texture.png"];
        texture.layer.cornerRadius = 20;
        texture.layer.masksToBounds = YES;
        [self.scrollV addSubview:texture];
        [texture release];
        UIImageView *textureScore = [[UIImageView alloc] initWithFrame:CGRectMake(texture.frame.origin.x+50, 275, 20, 30)];
        NSString *ts3 = [[self.dataDic objectForKey:@"dish_detail_item"] objectForKey:@"texture_score"];
        NSInteger a3 = [ts integerValue];
        if (a3 == 5) {
            textureScore.image = [UIImage imageNamed:@"scoreFive"];
        }else if (a3 == 4) {
            textureScore.image = [UIImage imageNamed:@"scoreFour"];
        }else if (a3 == 3) {
            textureScore.image = [UIImage imageNamed:@"scoreThree"];
        }else if (a3 == 2) {
            textureScore.image = [UIImage imageNamed:@"scoreTwo"];
        }else if (a3 == 1) {
            textureScore.image = [UIImage imageNamed:@"scoreOne"];
        }else if ((a3 == 0) || ts3 == nil) {
            textureScore.image = [UIImage imageNamed:@"scoreZero.png"];
        }
        [self.scrollV addSubview:textureScore];
        [textureScore release];
        
        //菜名&图
        
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(40, dishPic.frame.origin.y+dishPic.frame.size.height+10, 300, 20)];
        name.text = [[self.dataDic objectForKey:@"dish_detail_item"] objectForKey:@"dish_name"];
        name.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];
        [self.scrollV addSubview:name];
        [name release];
        UIImageView *namePic = [[UIImageView alloc] initWithFrame:CGRectMake(15, name.frame.origin.y, 20, 20)];
        namePic.image = [UIImage imageNamed:@"dishPic.png"];
        [self.scrollV addSubview:namePic];
        [namePic release];
        
        //地址&图
        
        UIImageView *locationPic = [[UIImageView alloc] initWithFrame:CGRectMake(15, namePic.frame.origin.y+25, 20, 20)];
        locationPic.image = [UIImage imageNamed:@"locaPic.png"];
        [self.scrollV addSubview:locationPic];
        [locationPic release];
        UILabel *location = [[UILabel alloc] initWithFrame:CGRectMake(40, locationPic.frame.origin.y, 300, 20)];
        location.text = [[self.dataDic objectForKey:@"dish_detail_item"] objectForKey:@"shop_name"];
        //location.text = self.favoCount;
        location.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
        [self.scrollV addSubview:location];
        [location release];
        
        //点赞数&图
        
        UIImageView *favoPic = [[UIImageView alloc] initWithFrame:CGRectMake(15, locationPic.frame.origin.y+25, 20, 20)];
        favoPic.image = [UIImage imageNamed:@"favorite.png"];
        [self.scrollV addSubview:favoPic];
        [favoPic release];
        UILabel *favoCount = [[UILabel alloc] initWithFrame:CGRectMake(40, favoPic.frame.origin.y, 300, 20)];
        NSString *ac = [[self.dataDic objectForKey:@"awardedcount_item"] objectForKey:@"awardcount"];
        if (ac == nil) {
            favoCount.text = @"0 人点赞";
        } else {
            favoCount.text = [NSString stringWithFormat:@"%@ 人喜爱", ac];
        }
        favoCount.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
        [self.scrollV addSubview:favoCount];
        [favoCount release];
        
        
        //热门店铺
        UIImageView *hotShopPic = [[UIImageView alloc] initWithFrame:CGRectMake(15, favoPic.frame.origin.y+25, 20, 20)];
        hotShopPic.image = [UIImage imageNamed:@"hotShopPic.png"];
        [self.scrollV addSubview:hotShopPic];
        [hotShopPic release];
        UIButton *hotShop = [UIButton buttonWithType:UIButtonTypeSystem];
        hotShop.frame = CGRectMake(40, hotShopPic.frame.origin.y, 200, 20);
        hotShop.backgroundColor = [UIColor colorFromHexCode:@"#33475f"];
        [hotShop setTitle:@"人气店铺" forState:UIControlStateNormal];
        [hotShop addTarget:self action:@selector(HotShopButtonAction) forControlEvents:UIControlEventTouchUpInside];
        hotShop.layer.cornerRadius = 10;
        [self.scrollV addSubview:hotShop];
        
        //点击热门店铺图片方法
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(HotShopButtonAction)];
        
        UIImageView *hotShopPic2 = [[UIImageView alloc] initWithFrame:CGRectMake(250, hotShop.frame.origin.y, 20, 20)];
        hotShopPic2.image = [UIImage imageNamed:@"dotdotdot.png"];
        hotShopPic2.userInteractionEnabled = YES;
        [hotShopPic2 addGestureRecognizer:tap];
        [self.scrollV addSubview:hotShopPic2];
        [hotShopPic2 release];
        
        UIImageView *hotShopPic3 = [[UIImageView alloc] initWithFrame:CGRectMake(270, hotShopPic2.frame.origin.y, 20, 20)];
        hotShopPic3.image = [UIImage imageNamed:@"right.png"];
        hotShopPic3.userInteractionEnabled = YES;
        [hotShopPic3 addGestureRecognizer:tap];
        [self.scrollV addSubview:hotShopPic3];
        [hotShopPic3 release];
        //tap需要release
        [tap release];
        //店铺
        NSArray *array = [NSArray array];
        array = [self.dataDic objectForKey:@"hot_shop_item"];
        for (NSInteger i = 0; i < array.count; i++) {
            
            HotShop *shopOne = [[HotShop alloc] initWithFrame:CGRectMake(20, hotShopPic.frame.origin.y+25+i*60, self.scrollV.frame.size.width-40, 60)];
            shopOne.hotShopName.text = [array[i] objectForKey:@"name"];
            NSString *str = [NSString stringWithFormat:@"￥%ld/人", (long)[[array[i] objectForKey:@"arg_spend"] integerValue]];
            shopOne.hotShopFee.text = str;
            shopOne.hotShopLocation.text = [array[i] objectForKey:@"address"];
            shopOne.layer.borderWidth = 1;
            shopOne.layer.borderColor = [[UIColor lightGrayColor] CGColor];
            shopOne.layer.cornerRadius = 5;
            [self.scrollV addSubview:shopOne];
            [shopOne release];
            
        }
        
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"shopDetailBackG.jpg"]];
        self.scrollV.backgroundColor = [UIColor clearColor];
        self.scrollV.contentSize = CGSizeMake(self.view.frame.size.width, 630);
        [self.view addSubview:self.scrollV];
        [_scrollV release];
        
        //返回主页
        UIImageView *backMain = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-15, 30, 30, 30)];
        backMain.image = [UIImage imageNamed:@"backToRe2.png"];
        backMain.layer.masksToBounds = YES;
        backMain.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapMain = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backMain)];
        [backMain addGestureRecognizer:tapMain];
        [tapMain release];
        [self.view addSubview:backMain];
        [backMain release];
        
        //自定义的返回按钮
        UIView *back = [[UIView alloc] initWithFrame:CGRectMake(10, 30, 30, 30)];
        back.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backToRecomm.png"]];
        back.layer.masksToBounds = YES;
        back.layer.cornerRadius = 15;
        back.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackAction)];
        [back addGestureRecognizer:tap2];
        [tap2 release];
        [self.view addSubview:back];
        [back release];
        
        [_HUD hide:YES];
        //----------------------------
        self.nameTitle = [[self.dataDic objectForKey:@"dish_detail_item"] objectForKey:@"dish_name"];
        NSLog(@"wowo%@", self.nameTitle);
        //收藏的改动
        self.myFavorImageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH - 30, 30, 30, 30)];
        
        self.myFavorImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapNu = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [self.myFavorImageView addGestureRecognizer:tapNu];
        [tapNu release];
        self.myFavorImageView.image = [UIImage imageNamed:@"favorite.png"];
        [self.view addSubview:self.myFavorImageView];
        [self.view bringSubviewToFront:self.myFavorImageView];
        [_myFavorImageView release];
        NSMutableArray *favArr = [NSMutableArray array];
        favArr = [[DataBaseHandler shareInstance] selectAll];
        Food *food = [[Food alloc] init];
        for (food in favArr) {
            if ([food.foodStr isEqualToString:self.num]) {
                self.myFavorImageView.image = [UIImage imageNamed:@"favorite2.png"];
                UITapGestureRecognizer *tapHa = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction2:)];
                [self.myFavorImageView addGestureRecognizer:tapHa];
                [tapHa release];
            }
        }
        
        UIButton *buttonShare = [UIButton buttonWithType:UIButtonTypeSystem];
        buttonShare.frame = CGRectMake(WIDTH - 100, 30, 30, 30);
        [buttonShare setTitle:@"分享" forState:UIControlStateNormal];
        [buttonShare addTarget:self action:@selector(buttonShareAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:buttonShare];
        //--------------------------------

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败");
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    NSString *str1 = @"http://yinweiapi.paidui.com:81/jms/fetchData.do?procedureName=app_share_dish_detail&parameters=%7B%22_member_id%22%3A%220%22%2C%22_member_share_id%22%3A%22";
    NSString *str2 = self.num;
    NSString *str3 = @"%22%7D";
    NSString *str = [NSString stringWithFormat:@"%@%@%@",str1,str2,str3];
    
    NSLog(@"%@", str);
    [self startAnalyze:str];
    
    self.HUD = self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    _HUD.labelText = @"Loading";
    //_HUD.color = [UIColor clearColor];
    _HUD.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_HUD];
    [_HUD release];
    [_HUD show:YES];
    //-----
    self.str = str;
    
    //返回主页
    UIImageView *backMain = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-15, 30, 30, 30)];
    backMain.image = [UIImage imageNamed:@"backToRe2.png"];
    backMain.layer.masksToBounds = YES;
    backMain.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapMain = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backMain)];
    [backMain addGestureRecognizer:tapMain];
    [tapMain release];
    [self.view addSubview:backMain];
    [backMain release];
    
    //自定义的返回按钮
    UIView *back = [[UIView alloc] initWithFrame:CGRectMake(10, 30, 30, 30)];
    back.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backToRecomm.png"]];
    back.layer.masksToBounds = YES;
    back.layer.cornerRadius = 15;
    back.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackAction)];
    [back addGestureRecognizer:tap2];
    [tap2 release];
    [self.view addSubview:back];
    [back release];
    
}
//--------------------
- (UIImage *)imageFromView:(UIView *)theView
{
    UIGraphicsBeginImageContext(theView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [theView.layer renderInContext: context];
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
- (void)buttonShareAction:(UIButton *)button
{
//    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK" ofType:@"png"];
    UIImage *shareimage =  [self imageFromView:self.view];
    NSURL *url = [NSURL URLWithString:self.str];
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:@"分享内容"
                                       defaultContent:@"测试一下"
                                                image:[ShareSDK pngImageWithImage:shareimage]
                                                title:@"美食"
                                                  url:self.str
                                          description:nil
                                            mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
        [container setIPadContainerWithView:button arrowDirect:UIPopoverArrowDirectionUp];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功" message:@"成功了哦" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                                    [alertView show];
                                    [self.view addSubview:alertView];
                                    [alertView release];
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败了" message:@"再试一次" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                                    [alertView show];
                                    [self.view addSubview:alertView];
                                    [alertView release];
                                }

                            }];
}


- (void)tapAction:(UITapGestureRecognizer *)tap
{
    Food *food = [[Food alloc] init];
    food.foodStr = self.num;
    food.nameLabel = self.nameTitle;
//    food.nameLabel = self.nameTitle;
    if (self.flag == NO) {
        [[DataBaseHandler shareInstance] insertFood:food];
        NSLog(@"%@", [[DataBaseHandler shareInstance] selectAll]);
        self.myFavorImageView.image = [UIImage imageNamed:@"favorite2.png"];
    } else {
        NSLog(@"---%@", food.foodStr);
        [[DataBaseHandler shareInstance] deleteFood:food];
        NSLog(@"%@", [[DataBaseHandler shareInstance] selectAll]);
        self.myFavorImageView.image = [UIImage imageNamed:@"favorite.png"];
    }
    self.flag = !self.flag;
    
}
- (void)tapAction2:(UITapGestureRecognizer *)tap
{
    Food *food = [[Food alloc] init];
    food.foodStr = self.num;
    food.nameLabel = self.nameTitle;
    if (self.flag == NO) {
        NSLog(@"---%@", food.foodStr);
        [[DataBaseHandler shareInstance] deleteFood:food];
        NSLog(@"%@", [[DataBaseHandler shareInstance] selectAll]);
        self.myFavorImageView.image = [UIImage imageNamed:@"favorite.png"];
    } else {
        [[DataBaseHandler shareInstance] insertFood:food];
        NSLog(@"%@", [[DataBaseHandler shareInstance] selectAll]);
        self.myFavorImageView.image = [UIImage imageNamed:@"favorite2.png"];
    }
    self.flag = !self.flag;
    
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

//-----------

- (void)backMain
{
    [self.navigationController popToRootViewControllerAnimated:NO];
}
- (void)tapBackAction
{
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)HotShopButtonAction
{
    HotShopsViewController *hs = [[HotShopsViewController alloc] init];
    hs.num = [[self.dataDic objectForKey:@"dish_detail_item"] objectForKey:@"member_share_id"];
    hs.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:hs animated:NO];
    //hs.hidesBottomBarWhenPushed = NO;
    [hs release];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
